import React, { useState,useEffect,useContext } from 'react'
import './Detail.less'
import Header from '../../components/Header/Header'
import {reqgetgoodsinfo,reqcartadd} from '../../http/api'
import { $pre } from '../../http/http'
import {Toast,Button} from 'antd-mobile'
import {MyContext} from '../../App'
export default function Detail(props) {
  let [goods,setGoods] = useState({});
  let {id,type} = props.match.params;
  let {state:{userInfo:{uid}}} = useContext(MyContext);
  let getDetail = async ()=>{
    let {data:res} = await reqgetgoodsinfo({id});
    if(res.code === 200){
      let obj = res.list[0] ? res.list[0] : {};
      setGoods(obj);
    }
  }
  let addCart = async ()=>{
    let {data:res} = await reqcartadd({uid,type,goodsid:id,num:1});
    if(res.code === 200){
      Toast.show({content:res.msg});
      props.history.push('/index/shop');
    }
    
  }
  useEffect(()=>{
    getDetail();
  },[])
  return (
    <div className='detail'>
      <Header back title='商品详情'></Header>
      {goods.id ? (<div>
        <img src={$pre + goods.img} alt="" />
        <p>商品名称：{goods.goodsname}</p>
        <p>商品价格：￥{goods.price}</p>
        <div><Button shape='rounded' color='warning' onClick={()=> addCart()}>加入购物车</Button><Button shape='rounded' color='danger' >立即购买</Button></div>
      </div>) : (<div>暂无数据</div>)}
    </div>
  )
}

